#include "face.h"
#include <opencv2/opencv.hpp>

using namespace cv;
using namespace std;
using namespace aip;

void mark(Mat& image, 
          double left, 
          double top, 
          double width, 
          double height, 
          int64_t rotation, 
          const Scalar& color, 
          int thickness)
{
    //将人脸区域扩大4倍之后，以原区域的左上角作为原点进行旋转
    RotatedRect rRect = RotatedRect(Point2f(left, top), Size2f(2*width, 2*height), rotation);
    Point2f vertices[4];
    rRect.points(vertices); //获取旋转后矩形的4个顶点

    Point2f bl = (vertices[3] + vertices[0])/2; //计算旋转后的左下角（线段中点）
    Point2f tl = Point2f(left, top);//左上角
    Point2f tr = (vertices[2] + vertices[3])/2;//右上角
    Point2f br = vertices[3]; //右下角

    line(image, bl, tl, color, thickness, CV_AA);
    line(image, tl, tr, color, thickness, CV_AA);
    line(image, tr, br, color, thickness, CV_AA);
    line(image, br, bl, color, thickness, CV_AA);
}

int main()
{
    Mat pic = imread("avengers.jpg");

    string appid = "18003626";
    string apikey = "kIGVsMnZEKqCfLfnl9op20cq";
    string secretkey = "udOcOUcZ1sRVG40sHTm5x4FzjiUxmpUh";
    //创建人脸识别客户端
    Face client(appid, apikey, secretkey);

    string image;
    get_file_content("avengers.jpg", &image);

    map<string, string> options;
    options["max_face_num"] = "10";  //在线API最多识别10张脸
    options["max_user_num"] = "10";

    string base64 = base64_encode(image.c_str(), image.size());
    Json::Value result = client.multi_search(base64, "BASE64", "Avengers", options);

    cout << result.toStyledString() << endl;

    Json::Value face_list = result["result"]["face_list"];
    for (unsigned int i = 0; i < face_list.size(); i++)
    {
        double x = face_list[i]["location"]["left"].asDouble();
        double y = face_list[i]["location"]["top"].asDouble();
        double h = face_list[i]["location"]["height"].asDouble();
        double w = face_list[i]["location"]["width"].asDouble();
        int64_t r = face_list[i]["location"]["rotation"].asInt();

        printf("x:%f, y:%f, w:%f, h:%f, r:%d\n", x, y, w, h, r);
        
        mark(pic, x, y, w, h, r, Scalar(0, 0, 255), 5);

        if (face_list[i]["user_list"].size())
        {
            cout << face_list[i]["user_list"][0]["user_id"].asString() << endl;
        }
    }

    imwrite("output.jpg", pic);
}